#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QMessageBox>
#include <QThread>

#include "Core/CvCommand.h"

const Status statuses[] = {
    { "M", UTF8("Изменён") },
    { "A", UTF8("Добавлен") },
    { "*", UTF8("Отличается") },
    { "?", UTF8("Не добавлен") }
};

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow),
    _statusTimerId(0) {
    ui->setupUi(this);
    CvCommand::setWorkingDir("D:\\googlecode\\cvSiren\\cvsiren");
    for (Status status : statuses) {
        _statuses[status.key] = status.value;
    }
}

MainWindow::~MainWindow() {
    delete ui;
}

void MainWindow::on_actStart_triggered() {
    onStatusTimerUpdate();
}

void MainWindow::on_actStop_triggered() {
    stopTimer(_statusTimerId);
}

void MainWindow::showMessage(QString message) {
    QMessageBox::warning(this, "Внимание!", message);
}

void MainWindow::timerEvent(QTimerEvent *ev) {
    if (ev->timerId() == _statusTimerId) {
        onStatusTimerUpdate();
    }
}

void MainWindow::stopTimer(TimerId & id) {
    if (id) {
        killTimer(id);
        id = 0;
    }
}

void MainWindow::log(QString text, bool brace) {
    if (brace) {
        text = QString("================ %1 ================").arg(text);
    }
    ui->editLog->appendPlainText(text);
}

void MainWindow::onUpdateFinished() {
    if (CvCommand * command = qobject_cast<CvCommand *>(sender())) {
        QString result = command->getResult();
        if (command->getStatus() == CommandResult::Error) {
            showMessage(result);
        } else {
            log(result, false);
            FillTreeFromUpdate(result);
        }
        command->finish();
    }
    setTimer(_statusTimerId, 5000);
}

void MainWindow::makeCommand(QString command, QString slot) {
    QThread* thread = new QThread();
    CvCommand* worker = new CvCommand(command);
    worker->moveToThread(thread);
    connect(thread, SIGNAL(started()), worker, SLOT(process()));
    connect(worker, SIGNAL(killThread()), thread, SLOT(quit()));
    connect(worker, SIGNAL(finished()), this, slot.toAscii());
    connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
    thread->start();
}

void MainWindow::FillTreeFromUpdate(QString fileInfo) {
    log("tree generating");
    ui->treeCv->clear();
    for (QString file : fileInfo.split("\n")) {
        QStringList info = file.simplified().split(" ");
        if (info.count() < 1) { //TODO: структура статусов, или, даже стратегии
            continue;
        }
        QString status = info.takeFirst();
        if (_statuses.keys().contains(status)) {
            QString revision = status == "?" ? status : info.takeFirst();
            QString fileName = info.takeFirst();
            QTreeWidgetItem * item = new QTreeWidgetItem(ui->treeCv);
            item->setText(0, fileName);
            item->setText(1, _statuses[status]);
            item->setText(3, revision);
        }
    }
}

void MainWindow::onStatusTimerUpdate() {
    log("update");
    stopTimer(_statusTimerId);

    makeCommand("svn status -u", SLOT(onUpdateFinished()));
}

void MainWindow::setTimer(TimerId &id, int interval) {
    if (id) {
        stopTimer(id);
    }
    id = startTimer(interval);
}
